package riven.controller;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import riven.manager.RedissonManager;

import java.util.concurrent.TimeUnit;

/**
 * @author 陈浩
 * @date 2021/12/9
 */
@RestController
public class RedissonController {

    /************************ 对象桶 **************************/
    @GetMapping("/get")
    public String get() {
        RBucket<Student> bucket = RedissonManager.getClient().getBucket("student");
        bucket.set(Student.of(24, "陈浩"));
        Student student = bucket.get();
        System.out.println(student);
        return "";
    }

    /************************ redisson自带的分布式自增 **************************/
    @GetMapping("/set")
    public void set() {
        RAtomicLong atomicLong = RedissonManager.getClient().getAtomicLong("myAtomicLong");
        atomicLong.set(0);
    }

    @GetMapping("/atomicLongTest")
    public Long atomicLongTest() {
        RAtomicLong atomicLong = RedissonManager.getClient().getAtomicLong("myAtomicLong");
        atomicLong.incrementAndGet();
        return atomicLong.get();
    }

    /************************ 使用redisson分布式锁实现自增 **************************/
    @GetMapping("/setBucket")
    public void setBucket() {
        RBucket<String> bucket = RedissonManager.getClient().getBucket("bucketTest");
        bucket.set("0");
    }

    @GetMapping("/distribute")
    public void distribute() throws InterruptedException {
        RLock lock = RedissonManager.getClient().getLock("anyLock");
        // 请求来到之后如果没有获取到锁，最多会排队等待100s；
        // 如果请求拿到了锁，那么这个请求最多持有锁10s，10s后自动解锁
        boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
        if (res) {
            try {
                lockTest();
            } finally {
                lock.unlock();
            }
        }
    }

    private void lockTest() {
        RBucket<String> bucket = RedissonManager.getClient().getBucket("bucketTest");
        String value = bucket.get();
        bucket.set(String.valueOf(Long.parseLong(value) + 1));
    }

}
